<?php
/**
 * Created by PhpStorm.
 * User: Aliaksei Lazerka
 * Date: 10/6/14
 * Time: 8:13 PM
 */

namespace sql;

if (!defined('NYMPH_ROOT')) {
  define('NYMPH_ROOT', dirname("../../" . __FILE__));
  require(NYMPH_ROOT . '/local/loader/kernel/classes/URLClassLoader.php');
}

/**
 * Used for storing and manipulating named queries
 */
class NamedSQLStorage
{

  /**
   * @var array associative array
   * key: query name
   * value: SimpleSQLQuery
   */
  private $queries;


  /**
   * @var XMLParserImpl
   */
  private $parser;

  /**
   * (PHP 5)<br/>
   * @param XMLParserImpl $xmlParser
   */
  function __construct($xmlParser)
  {
    $this->parser = $xmlParser;
    $this->queries = $this->parser->parseAll();
  }

  /**
   * (PHP 5)<br/>
   * @param SimpleSQLQuery $sqlQuery
   * @param string $name
   */
  public function addQuery($sqlQuery, $name)
  {
    $this->queries["'" . $name . "'"] = $sqlQuery;
  }

  /**
   * (PHP 5)<br/>
   * @param string $name
   * @param Params $params
   * @return string query
   */
  public function getQuery($name, $params)
  {
    $query = null;
    foreach ($this->queries as $key => $value) {
      $body = $value->getQueryBody();
      if ($key == "'" . $name . "'") {
        $query = $body;
        break;
      }
    }

    if ($params != null) {
      return ParamResolver::resolveQuery($query, $params);
    } else {
      return $query;
    }
  }
} 